package com.cyc.forkJoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class tesk {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //test1();    //使用时间为:11423 结果为:500000000500000000
        test2();    //使用时间为:8956 结果为:500000000500000000
        //test3();      //使用时间为:1072 结果为:500000000500000000
    }

    //直接累加
    public static void test1(){
        Long s = System.currentTimeMillis();
        Long sum = 0L;
        for (int i = 1; i <= 10_0000_0000; i++) {
            sum += i;
        }
        Long e = System.currentTimeMillis();
        System.out.println("使用时间为:"+(e-s)+" 结果为:"+sum);
    }

    //使用ForkJoin  可以调优
    public static void test2() throws ExecutionException, InterruptedException {
        Long s = System.currentTimeMillis();
        //实例ForkJoinPool
        ForkJoinPool forkJoinPool  = new ForkJoinPool();
        //实例RecursiveTask
        ForkJoinDemo forkJoinDemo = new ForkJoinDemo(1L,10_0000_0000L);
        //pool提交task  异步执行
        ForkJoinTask<Long> submit = forkJoinPool.submit(forkJoinDemo);
        //pool提交task  同步执行
//        forkJoinPool.execute(forkJoinDemo);
        //得到结果
        Long sum = submit.get();
        Long e = System.currentTimeMillis();
        System.out.println("使用时间为:"+(e-s)+" 结果为:"+sum);
    }

    //使用stream并行流
    public static void test3(){
        Long s = System.currentTimeMillis();
        long sum = LongStream.rangeClosed(1L,10_0000_0000L).parallel().reduce(0L, Long::sum);
        Long e = System.currentTimeMillis();
        System.out.println("使用时间为:"+(e-s)+" 结果为:"+sum);
    }

}
